import { useEffect, useState, useRef } from 'react'
import { NavBar, Input, List, Empty, Toast, Skeleton } from 'antd-mobile'
import { SearchOutline, CloseOutline, DeleteOutline, RedoOutline } from 'antd-mobile-icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { 
  getSearchSuggestions, 
  getHotSearches, 
  searchContent,
  type SearchSuggestionItem
} from '../../api/searchService'
import { debounce } from '../../utils/debounce'
import styles from './search.module.scss'

const SearchPage = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const inputRef = useRef<any>(null)

  // 状态管理
  const [keyword, setKeyword] = useState('')
  const [suggestions, setSuggestions] = useState<SearchSuggestionItem[]>([])
  const [hotSearches, setHotSearches] = useState<any[]>([])
  const [searchHistory, setSearchHistory] = useState<string[]>([])
  const [searchResult, setSearchResult] = useState<{
    articles?: any[]
    htmlContent?: string
  }>({})
  const [isLoading, setIsLoading] = useState({
    suggest: false,
    hot: false,
    result: false
  })
  const [hasSearched, setHasSearched] = useState(false)

  // 防抖的搜索建议获取函数
  const debouncedGetSuggestions = debounce(async (value: string) => {
    setIsLoading(prev => ({ ...prev, suggest: true }))
    try {
      const res = await getSearchSuggestions(value)
      setSuggestions(res)
    } catch (error) {
      console.error('获取搜索建议失败:', error)
      setSuggestions([])
    } finally {
      setIsLoading(prev => ({ ...prev, suggest: false }))
    }
  }, 1000)

  // 输入框变化处理
  const handleInputChange = (value: string) => {
    setKeyword(value)
    setHasSearched(false)

    if (!value.trim()) {
      setSuggestions([])
      return
    }

    debouncedGetSuggestions(value.trim())
  }

  // 搜索提交处理
  const handleSearchSubmit = async () => {
    if (!keyword?.trim()) return

    const trimmedKeyword = keyword.trim()
    addToSearchHistory(trimmedKeyword)
    setIsLoading(prev => ({ ...prev, result: true }))
    setHasSearched(true)

    try {
      const res = await searchContent(trimmedKeyword)
      
      if (typeof res === 'string' && (res as string).includes('<!DOCTYPE html>')) {
        setSearchResult({
          htmlContent: res,
          articles: []
        })
        return
      }
      
      setSearchResult({
        articles: Array.isArray(res) ? res : []
      })
    } catch (error) {
      Toast.show({ content: '搜索失败，请稍后重试', duration: 1500 })
      setSearchResult({})
    } finally {
      setIsLoading(prev => ({ ...prev, result: false }))
    }
  }

  // 3. 清除输入：清空关键词 + 聚焦输入框
  const handleClear = () => {
    setKeyword('')
    setSuggestions([])
    setHasSearched(false)
    inputRef.current?.focus()
  }

  // 4. 添加搜索历史
  const addToSearchHistory = (searchKeyword: string) => {
    const newHistory = [searchKeyword, ...searchHistory.filter(item => item !== searchKeyword)].slice(0, 10)
    setSearchHistory(newHistory)
    localStorage.setItem('searchHistory', JSON.stringify(newHistory))
  }

  // 5. 清空搜索历史
  const clearSearchHistory = () => {
    setSearchHistory([])
    localStorage.removeItem('searchHistory')
  }

  // 6. 点击搜索建议/热门词：自动填充关键词并搜索
  const handleWordClick = (word: string) => {
    setKeyword(word)
    addToSearchHistory(word) // 添加到搜索历史
    handleSearchSubmit() // 直接触发搜索
  }

  // 5. 返回上一页（保留原有逻辑）
  const handleBack = () => {
    const from = location.state?.from
    if (from) {
      navigate(from)
    } else {
      try {
        navigate(-1)
      } catch (error) {
        navigate('/')
      }
    }
  }

  // 6. 页面初始化：从URL获取初始关键词 + 加载热门搜索 + 加载搜索历史
  useEffect(() => {
    // 加载搜索历史
    const savedHistory = localStorage.getItem('searchHistory')
    if (savedHistory) {
      setSearchHistory(JSON.parse(savedHistory))
    }

    // 加载热门搜索
    const fetchHotSearches = async () => {
      setIsLoading(prev => ({ ...prev, hot: true }))
      try {
        const res = await getHotSearches()
        setHotSearches(res)
      } catch (error) {
        console.error('获取热门搜索失败:', error);
        // 出错时设置为空数组
        setHotSearches([])
      } finally {
        setIsLoading(prev => ({ ...prev, hot: false }))
      }
    }
    fetchHotSearches()

    // 从URL参数获取初始关键词（如分享链接带关键词）
    const params = new URLSearchParams(location.search)
    const initialKeyword = params.get('keyword')
    if (initialKeyword) {
      setKeyword(initialKeyword)
      handleSearchSubmit() // 有初始关键词时自动搜索
    }

    // 输入框自动聚焦
    inputRef.current?.focus()

    // 组件卸载时清理
    return () => {
      // 清理工作
    }
  }, [location.search])



  // 渲染搜索结果（按分类展示：文章）
  const renderSearchResult = () => {
    const articles = Array.isArray(searchResult.articles) ? searchResult.articles : []
    const hasResult = articles.length || searchResult.htmlContent

    if (isLoading.result) {
      // 加载中：显示骨架屏
      return <Skeleton className={styles.skeleton} />
    }

    if (!hasResult) {
      // 无结果：显示空状态
      return <Empty description="未找到相关内容" className={styles.empty} />
    }

    // 如果有HTML内容，渲染HTML页面
        if (searchResult.htmlContent) {
          return (
            <div className={styles.htmlResultContainer}>
              <div 
                className={styles.htmlContent}
                dangerouslySetInnerHTML={{ __html: searchResult.htmlContent }}
              />
            </div>
          )
        }

    // 有结果：分类渲染
    return (
      <div className={styles.resultContainer}>
        {/* 文章结果 */}
        {articles.length > 0 && (
          <div className={styles.resultSection}>
            <h3 className={styles.sectionTitle}>相关文章</h3>
            <List>
              {articles.map(item => (
                <List.Item
                  key={item.id}
                  title={item.title}
                  description={item.summary || '点击查看详情'}
                  onClick={() => navigate(`/article/${item.id}`)} // 跳转到文章详情页
                  className={styles.resultItem}
                >
                  {item.cover_image && <img src={item.cover_image} alt="" className={styles.articleImg} />}
                </List.Item>
              ))}
            </List>
          </div>
        )}

      </div>
    )
  }

  return (
    <div className={styles.searchPage}>
      {/* 导航栏（保留原有） */}
      <NavBar back="返回" onBack={handleBack} />

      {/* 搜索输入区（保留原有结构，优化逻辑） */}
      <div className={styles.searchContainer}>
        <div className={styles.searchInputWrapper}>
          <SearchOutline className={styles.searchIcon} />
          <Input
            ref={inputRef}
            className={styles.searchInput}
            placeholder="阴道炎"
            value={keyword}
            onChange={handleInputChange}
            onEnterPress={handleSearchSubmit}
            clearable
          />
          {keyword && (
            <CloseOutline 
              className={styles.clearIcon} 
              onClick={handleClear}
            />
          )}
        </div>
        <button 
          className={styles.searchBtn}
          onClick={handleSearchSubmit}
        >
          搜索
        </button>
      </div>

      {/* 内容区：根据状态切换 建议/热门/结果 */}
      <div className={styles.contentContainer}>
        {/* 1. 搜索建议（输入有内容且未搜索时显示） */}
        {keyword && keyword.trim() && !hasSearched && (
          <div className={styles.suggestContainer}>
            {isLoading.suggest ? (
              <Skeleton className={styles.skeleton} />
            ) : suggestions.length > 0 ? (
              <div>
                {/* 如果有image类型的数据，显示第一个image在顶部 */}
                {suggestions.find(item => item.type === 'image')?.image && (
                  <div className={styles.suggestImageContainer}>
                    <img 
                      src={suggestions.find(item => item.type === 'image')?.image} 
                      alt="搜索建议图片" 
                      className={styles.suggestImage}
                    />
                  </div>
                )}
                {/* 搜索建议列表 - 只显示text类型的建议 */}
                <List>
                  {suggestions
                    .filter(item => item.type === 'text')
                    .map((item, index) => (
                    <List.Item
                      key={item.id || index}
                      title={item.title}
                      prefix={<SearchOutline className={styles.suggestIcon} />}
                      onClick={() => handleWordClick(item.title || '')}
                      className={styles.suggestItem}
                    />
                  ))}
                </List>
              </div>
            ) : (
              <div className={styles.noSuggest}>暂无相关搜索建议</div>
            )}
          </div>
        )}

        {/* 2. 历史搜索和热门搜索（输入为空时显示） */}
        {(!keyword || !keyword.trim()) && (
          <div className={styles.defaultContent}>
            {/* 历史搜索 */}
            {searchHistory.length > 0 && (
              <div className={styles.historySection}>
                <div className={styles.sectionHeader}>
                  <span className={styles.sectionTitle}>历史搜索</span>
                  <DeleteOutline 
                    className={styles.clearIcon} 
                    onClick={clearSearchHistory}
                  />
                </div>
                <div className={styles.tagContainer}>
                  {searchHistory.map((item, index) => (
                    <div
                      key={`history-${index}`}
                      className={styles.searchTag}
                      onClick={() => handleWordClick(item)}
                    >
                      {item}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 热门搜索 */}
            <div className={styles.hotSection}>
              <div className={styles.sectionHeader}>
                <span className={styles.sectionTitle}>热门搜索</span>
                <RedoOutline 
                  className={styles.refreshIcon} 
                  onClick={() => {
                    const fetchHotSearches = async () => {
                      setIsLoading(prev => ({ ...prev, hot: true }))
                      try {
                        const res = await getHotSearches()
                        setHotSearches(res || [])
                      } catch (error) {
                        Toast.show({ content: '获取热门搜索失败', duration: 1500 })
                      } finally {
                        setIsLoading(prev => ({ ...prev, hot: false }))
                      }
                    }
                    fetchHotSearches()
                  }}
                />
              </div>
              {isLoading.hot ? (
                <Skeleton className={styles.skeleton} />
              ) : (
                <div className={styles.tagContainer}>
                  {hotSearches && hotSearches.length > 0 ? (
                    hotSearches.map((item, index) => (
                      <div
                        key={`hot-${index}`}
                        className={styles.searchTag}
                        onClick={() => handleWordClick(item.recommend_word || item.title || item)}
                      >
                        <a href={item.url}>
                        {item.icon && (
                          <img 
                            src={item.icon} 
                            alt="icon" 
                            style={{ width: '16px', height: '16px', marginRight: '4px' }}
                          />
                        )}
                        {item.recommend_word || item.title || item}
                        </a>
                      </div>
                    ))
                  ) : (
                    <div className={styles.noHotSearch}>暂无热门搜索</div>
                  )}
                </div>
              )}
            </div>
          </div>
        )}

        {/* 3. 搜索结果（执行搜索后显示） */}
        {hasSearched && renderSearchResult()}
      </div>
    </div>
  )
}

export default SearchPage